<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <div class="searchFormBlend">
        <a-form-model ref="formRef" :model="form" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
          <a-row type="flex" justify="space-between">
            <a-col :span="20">
              <a-col :span="6">
                <Input :form="form" label="手机号码" prop="mobile" placeholder="请输入手机号码"></Input>
              </a-col>
              <!-- v-if="roleCode == 'admin'" -->
              <a-col :span="6">
                <treeSelect
                  :form="form"
                  label="所属组织"
                  prop="organizationId"
                  placeholder="请选择组织机构"
                  :treeData="organizationsTree"
                ></treeSelect>
              </a-col>
              <a-col :span="6">
                <div class="addBox" @click="onSubmit">
                  <a-button
                    type="primary"
                    shape="circle"
                    icon="plus"
                    style="background: #ffc600; border-color: #ffc600"
                  />
                  <span>新增白名单</span>
                </div>
              </a-col>
            </a-col>
            <a-col :span="4" style="display: flex; justify-content: flex-end">
              <Button type="search" @click="search"></Button>
              <Button
                type="reset"
                style="margin-left: 8px"
                @click="
                  () => {
                    form.mobile = undefined;
                    form.organizationId = undefined;
                  }
                "
              ></Button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="table">
        <div class="tableTitle">
          <div class="title">白名单管理</div>
          
          <div class="addButton">
            <span style="margin-right: 8px" v-show="selectedRowKeys.length > 0">
              {{ `当前选择 ${selectedRowKeys.length} 条数据` }}
            </span>
            <a-popconfirm
              slot="action"
              title="此操作将删除已勾选的数据，是否继续?"
              ok-text="是"
              cancel-text="否"
              @confirm="batchDel"
            >
              <Button
                type="batchDelete"
                label="批量删除"
                :disabled="selectedRowKeys.length === 0 || isLoading"
                :loading="isLoading"
              >
              </Button>
            </a-popconfirm>
          </div>
        </div>
        <div class="tableList">
          <typicalTable :key="'key'+keyNum"
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
            @selectionChange="tableChange"
          >
            <!-- <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit('modleVisible', slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
            </template> -->
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import Button from '@/components/typicalControl/button';
import treeSelect from '@/components/typicalControl/treeSelect';
import { recursionTreeDisabled } from '@/utils/tool';

import { listOrgAdditionalUsers } from '@/api/cabin';
import { organizationsTree } from '@/api/system';

export default {
  name: 'MessageManagement',
  components: {
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    Button: Button,
    treeSelect: treeSelect,
  },
  data() {
    return {
      isLoading: false, // 禁用按钮 防止多次点击多次保存
      roleLoading: false, // 加载表格的loading
      form: {
        mobile: undefined,
        organizationId: '',
      },
      organizationsTree: [], //组织机构
      rules: {
        // 规则验证
        mobile: [
          {
            pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
            message: '请输入正确格式的手机号码',
            trigger: 'blur',
          },
        ],
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '登录名',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '用户名',
            dataIndex: 'userName',
            ellipsis: true,
          },
          {
            title: '手机号',
            dataIndex: 'mobile',
            ellipsis: true,
          },
          {
            title: '组织机构',
            dataIndex: 'organizationName',
            ellipsis: true,
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        isSelection: true,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      selectedRowKeys: [],
      roleCode: this.$store.getters.userInfo.roleCode,
      keyNum:0,
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.search();
  },
  methods: {
    search() {
      this.$refs.insideTable.updateListData();
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      searchParam.searchMobile = this.form.mobile;
      let params = {
        pageNum: searchParam.pageNumber + 1,
        pageSize: searchParam.pageSize,
        mobile: searchParam.searchMobile ? searchParam.searchMobile : '',
        organizationId: this.form.organizationId ? this.form.organizationId : '',
      };
      listOrgAdditionalUsers('/selectChargingWhiteList', 'get', params)
        .then((res) => {
          if (res.code == 200 && res.data.records) {
            this.tableData = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    getDictionary() {
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          recursionTreeDisabled(res.data);
          this.organizationsTree = res.data;
        }
      });
    },
    /**
     * @description: 新增编辑白名单表单提交
     */
    onSubmit() {
      if (this.isLoading) {
        return;
      }
      if (!this.form.mobile) {
        return this.$message.error('请输入手机号码！');
      } else if (!this.form.organizationId) {
        return this.$message.error('请选择组织机构！');
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.roleAdd(this.form);
        } else {
          return false;
        }
      });
    },

    /**
     * [tableChange table多选变化]
     * @param  {[type]} index  [序号]
     * @param  {[type]} arrObj [数组对象]
     * @return {[type]}        [description]
     */
    tableChange(index, arrObj) {
      this.selectedRowKeys = arrObj.map((n) => {
        return n.id;
      });
    },

    /**
     * @description: 新增白名单权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      this.isLoading = true;
      listOrgAdditionalUsers(
        `/insertMobile?mobile=${addRoleParam.mobile}&organizationId=${addRoleParam.organizationId}`,
        'post'
      )
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.search();
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    /**
     * [batchDel 批量删除]
     * @return {[type]} [description]
     */
    batchDel() {
      this.isLoading = true;
      listOrgAdditionalUsers(`/deleteByIds?Ids=${this.selectedRowKeys}`, 'delete')
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.isLoading = false;
            this.selectedRowKeys = [];
            this.$refs.insideTable.setSelectedRowKeys(this.selectedRowKeys);
            this.keyNum++;
            this.search();
          }
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 50%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
.searchFormBlend {
  padding: 10px 10px 0;
  background: #fff;
  margin-bottom: 10px;
  border-radius: 5px;
}
.addBox {
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  margin-left: 10px;
}
.addBox span {
  margin-left: 5px;
}
</style>
